package com.example.tagsdemo.listener;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.tagsdemo.entity.ErrorExcel;
import com.example.tagsdemo.entity.Student;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class StudentDataListener  extends AnalysisEventListener<Student> {

    private static final int BATCH_COUNT = 3000;
    List<ErrorExcel> list = new ArrayList<>();

    String fileName = "E:\\error.xlsx";

    @Override
    public void invoke(Student s, AnalysisContext analysisContext) {

        check(s,analysisContext);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            EasyExcel.write(fileName, ErrorExcel.class).sheet("sheet0").doWrite(list);
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        EasyExcel.write(fileName, ErrorExcel.class).sheet("sheet0").doWrite(list);
        // 存储完成清理 list
        list.clear();
        log.info("所有数据解析完成！");
    }

    private void check(Student s,AnalysisContext analysisContext) {
        StringBuffer sb = new StringBuffer();


        if (StringUtils.isBlank(s.getName()) ){
            sb.append("name|");
        }
        if (null == s.getAge() ||  s.getAge().intValue() > 20){
            sb.append("age|");
        }

        if (null == s.getGender() ||  s.getGender() == 0){
            sb.append("gender|");
        }

//        if (null == s.getEmail()){
//            sb.append("email|");
//        }
        if (sb.length() > 0) {
            ErrorExcel error = new ErrorExcel();
            error.setMsg(sb.toString());
            error.setName(s.getName() +  "行号" + analysisContext.readRowHolder().getRowIndex());
            log.info("解析到一条错误数据:{},行数:{}", analysisContext.readRowHolder().getRowIndex());
            list.add(error);

        }
    }
}
